/*
 * =====================================================================================
 *
 *       Filename:  main.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2019年05月13日 11时37分15秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  YOUR NAME (), 
 *   Organization:  
 *
 * =====================================================================================
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <fcntl.h>
#include <sys/types.h>

/* 一个日志文件，固定大小 */
int open_create_file(const char *file_path)
{
    int fd = open(file_path, O_RDWR | O_CREAT, 0666);
    if(fd < 0) {
        perror("open");
    }
    return fd;
}

/*
 * limit: 是unsigned int,文件最大4个G
 */
int write_file_with_limit(int fd, unsigned int limit, const char *buff)
{
    /* 获取当前文件的偏移 */
    off_t offset = lseek(fd, 0, SEEK_CUR);
    //printf("Before Write, offset is %ld\n", offset);
    /* 如果偏移量+strlen(buff) <= limit: 写入buff */
    if(offset + strlen(buff) <= limit) {
        write(fd, buff, strlen(buff));
        offset = lseek(fd, 0, SEEK_CUR);
        //printf("After Write, offset is %ld\n", offset);
    }
    else {
        /* 设置偏移量为0 */
        offset = lseek(fd, 0, SEEK_SET);
        //printf("After lseek Set, offset is %ld\n", offset);
        write(fd, buff, strlen(buff));
        offset = lseek(fd, 0, SEEK_CUR);
        //printf("After Write, offset is %ld\n", offset);
    }
    //printf("\n");
    return 0;
}

const char *file_path = "log.log";
unsigned int limit = 1024 * 1024 * 100;

int main(int argc, char **argv)
{
    /* 创建文件 */
    int fd = open_create_file(file_path);
    if(fd < 0) {
        return -1;
    }
    /* 带限制写入文件 */
    int count = 0;
    while(1) {
        time_t t = time(NULL);
        char buff[64] = {0};
        sprintf(buff, "[%d] %s", count++, ctime(&t));
        write_file_with_limit(fd, limit, buff);
    }
    return 0;
}

